package com.geeyuu.android.service;

import java.util.ArrayList;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;

public abstract class BaseService extends Service {

    protected static String TAG = "BaseService";
    static final int MSG_REGISTER_CLIENT = 9991;
    static final int MSG_UNREGISTER_CLIENT = 9992;

    ArrayList<Messenger> mClients = new ArrayList<Messenger>();
    ArrayList<String> mClientTags = new ArrayList<String>();
    final Messenger mMessenger = new Messenger(new IncomingHandler(this));

    private static class IncomingHandler extends Handler {

        private final BaseService baseService;

        public IncomingHandler(BaseService service) {
            baseService = service;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_REGISTER_CLIENT:
                baseService.mClients.add(msg.replyTo);
                baseService.mClientTags.add((String) msg.obj);
                break;
            case MSG_UNREGISTER_CLIENT:
                baseService.mClients.remove(msg.replyTo);
                baseService.mClientTags.remove(msg.obj);
                break;
            default:
                baseService.onReceiveMessageFromActivity(msg);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        onStartService();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        onStopService();
    }

    protected void sendMsgToClient(Message msg) {
        final int clientCount = mClients.size();
        final String tag = (String) msg.obj;
        for (int i = 0; i < clientCount; i++) {
            try {
                if (tag.equals(mClientTags.get(i))) {
                    Messenger messenger = mClients.get(i);
                    messenger.send(msg);
                    break;
                }
            } catch (Exception e) {
                mClients.remove(i);
            }
        }
    }

    public abstract void onStartService();

    public abstract void onStopService();

    public abstract void onReceiveMessageFromActivity(Message msg);

}
